package org.abratuhi.kvngroupware.jokemanager.mptua;

import java.util.List;
import java.util.Properties;

import org.abratuhi.kvngroupware.jokemanager.manager.JokeManager;
import org.abratuhi.kvngroupware.jokemanager.model.Joke;
import org.abratuhi.kvngroupware.login.manager.LoginManager;
import org.abratuhi.kvngroupware.network.AbstractResponseMessageProceeder;
import org.abratuhi.kvngroupware.network.Client;
import org.abratuhi.kvngroupware.network.Message;
import org.abratuhi.kvngroupware.network.MessageSender;
import org.abratuhi.kvngroupware.widget.WidgetManager;
import org.jdom.Element;

public class JokemanagerResponseMessageProceeder extends AbstractResponseMessageProceeder{
	LoginManager loginmanager;
	JokeManager jokemanager;
	WidgetManager widgetmanager;

	public JokemanagerResponseMessageProceeder(MessageSender sender, Properties locale, LoginManager loginmanager, JokeManager jokemanager, WidgetManager widgetmanager){
		super(sender, locale);
		this.loginmanager = loginmanager;
		this.jokemanager = jokemanager;
		this.widgetmanager = widgetmanager;
	}

	@Override
	public void proceedMessage(Client client, Message message) {
		Element response = ((Element) message.getRoot().getChildren("response").get(0));
		String type = response.getAttributeValue("type");
		String action = response.getAttributeValue("action");

		if(type.equals("joke")){
			String teamId = response.getAttributeValue("teamId");
			String userId = response.getAttributeValue("userId");
			String jokeId = response.getAttributeValue("jokeId");
			String status = response.getAttributeValue("status");
			Joke j = (response.getChildren().size() > 0) ? Joke.fromElement(response.getChild("joke")) : null;
			
			if(loginmanager.getTeam().getId().equals(teamId)){
				if(status.equals("ok")){
					if(action.equals("create")){
						jokemanager.put(jokeId, j);
					}
					else if(action.equals("get")){
						List<Element> jokes = response.getChildren("joke");
						jokemanager.clear();
						for(int i=0; i<jokes.size(); i++) {
							Joke joke = Joke.fromElement(jokes.get(i));
							jokemanager.put(joke.getId(), joke);
						}
					}
					else if(action.equals("update")){
						jokemanager.update(j.getId(), j);
					}
					else if(action.equals("delete")){
						jokemanager.remove(jokeId);
					}
				}
			}
		}
	}

}
